package com.gree.elasticsearch.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gree.elasticsearch.dto.Result;
import com.gree.elasticsearch.security.JwtService;
import io.jsonwebtoken.Jwt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 总有刁民想害朕，请叫我小花狗
 * create by zxw on 2020/5/30
 */
@Component(value = "customerAuthenticationSuccessHandler")
public class CustomerAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    private Logger log = LoggerFactory.getLogger(CustomerAuthenticationSuccessHandler.class.getName());

    @Autowired
    private JwtService jwtService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        log.debug("username and password authentication success");
        String token = jwtService.createJwt(authentication);

        Result result = new Result(HttpStatus.OK.value(), token, "ok");

        ObjectMapper objectMapper = new ObjectMapper();
        String rsp = objectMapper.writeValueAsString(result);

        OutputStream outputStream = response.getOutputStream();
        outputStream.write(rsp.getBytes());
        outputStream.flush();
        outputStream.close();

    }
}
